<template>
  <view class="page-container">
    <!-- 顶部导航 - 固定部分 -->
    <view class="fixed-header">
      <S1Header title="批次详情" :on-back="onBack" />

      <!-- 批次头部信息 -->
      <view class="batch-header relative">
        <!-- 在售标签 -->
        <view class="status-tag">
          <text class="text-xs text-black">
            在售
          </text>
        </view>

        <view class="h-full flex items-center justify-between px-4">
          <!-- 左侧信息区域 -->
          <view class="mt-1 flex flex-col">
            <!-- 名字和批次号 -->
            <view class="flex items-center">
              <text class="text-lg text-white font-bold">
                {{
                  batchInfo.buyer
                }}
              </text>
              <view class="ml-2 rounded bg-gray-700 px-2 py-1 text-sm text-white">
                {{ batchInfo.batchNo }}
              </view>
            </view>

            <!-- 时间和操作员 -->
            <view class="mt-2 text-xs text-white">
              {{ batchInfo.time }} {{ batchInfo.operator }}
            </view>
          </view>

          <!-- 销售统计按钮 -->
          <view class="stats-btn flex items-center" @click="goToSalesStats">
            <text class="stats-text">
              销售统计
            </text>
            <text class="stats-text ml-1">
              >
            </text>
          </view>
        </view>
      </view>
    </view>

    <!-- 可滚动内容区域 -->
    <scroll-view scroll-y class="content-scroll">
      <!-- 未结算货品部分 -->
      <view class="bg-white px-4 py-3">
        <text class="text-base font-bold">
          未结算货品
        </text>
      </view>

      <!-- 商品表格 -->
      <view class="order-table">
        <!-- 表头 -->
        <view class="table-header">
          <view class="th goods-info">
            货品
          </view>
          <view class="th quantity">
            销量
          </view>
          <view class="th price">
            均价
          </view>
          <view class="th subtotal">
            货款
          </view>
        </view>

        <!-- 商品行 -->
        <view v-for="(item, index) in goodsList" :key="index" class="table-row">
          <view class="goods-info td">
            <view class="flex items-start">
              <text class="mr-1">
                {{ index + 1 }}.
              </text>
              <view class="max-w-full flex flex-col justify-center" @click="editGoods(item)">
                <text class="truncate">
                  {{ item.goods_name }}
                </text>

                <view
                  v-if="item.goods_guige && item.goods_guige.length > 0"
                  class="mt-1 flex items-center overflow-hidden text-xs"
                >
                  <view class="guige-tag overflow-hidden text-ellipsis">
                    <text v-for="(guige, gIndex) in item.goods_guige" :key="gIndex">
                      <text v-if="gIndex > 0" class="mx-1">
                        |
                      </text>
                      1{{ guige.relation }}={{ guige.num }}{{ guige.unit }}
                    </text>
                  </view>
                </view>
              </view>
            </view>
          </view>
          <view class="td quantity" @click="showGoodsDetail(item)">
            <text>{{ item.sell_str }}</text>
            <!-- <text v-if="item.average_weight" class="weight-text">({{ item.mini_type_num }}{{ item.mini_type }})</text> -->
          </view>
          <view class="td price" @click="showGoodsDetail(item)">
            {{ item.single }}
          </view>
          <view class="td subtotal" @click="showGoodsDetail(item)">
            {{ item.all_goods_price }}
          </view>
        </view>

        <!-- 合计行 -->
        <view class="total-row table-row">
          <view class="td goods-info">
            <view class="flex items-start">
              <text>合计</text>
            </view>
          </view>
          <view class="td quantity">
            <text>{{ statistics.sell_total_num }}</text>
            <!-- <text v-if="statistics.sell_total_weight" class="weight-text">{{ statistics.sell_total_weight }}</text> -->
          </view>
          <view class="td price">
            {{ statistics.single }}
          </view>
          <view class="td subtotal">
            {{ statistics.goods_total }}
          </view>
        </view>
      </view>

      <!-- 未结算费用 - 修改标题栏，添加按钮放在此处 -->
      <view class="fees-section">
        <view class="flex items-center justify-between px-4 py-3">
          <text class="text-base font-bold">
            未结算费用
          </text>
          <view class="add-btn" @click="goToAddFee">
            <text class="text-white">
              + 添加
            </text>
          </view>
        </view>

        <!-- 费用列表 -->
        <view v-for="(fee, index) in feesList" :key="index" class="fee-item">
          <view class="flex items-center justify-between">
            <text>{{ fee.name }}</text>
            <view class="flex">
              <text
                :class="fee.amount.startsWith('-') ? 'text-red-500' : 'text-green-500'
                "
              >
                {{ fee.amount }}
              </text>
              <view class="ml-2 flex">
                <view class="fee-edit-icon mr-2" />
                <view class="fee-delete-icon" @click="deleteFee(fee.id)" />
              </view>
            </view>
          </view>
          <view class="mt-1 text-xs text-gray-400">
            <text>{{ fee.time }} {{ fee.operator }}</text>
          </view>
        </view>

        <!-- 费用合计 -->
        <view class="fee-total">
          <text>合计:</text>
          <text class="ml-2 text-red-500">
            {{ totalFees }}
          </text>
        </view>
      </view>

      <!-- 备注区域 -->
      <view class="remark-area">
        <textarea v-model="remarkText" class="remark-textarea" placeholder="备注一下" auto-height />
      </view>

      <!-- 底部占位空间 -->
      <view style="height: 80px;" />
    </scroll-view>

    <!-- 底部操作栏 - 固定部分 -->
    <view class="fixed-footer">
      <view class="buttons-group">
        <button class="batch-sold-btn" @tap="onBatchSold">
          批次售完
        </button>
        <button class="settle-btn" @tap="onSettle">
          应结: <text class="text-yellow-400">
            {{ totalToSettle }}
          </text> 去结算
        </button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import type { GoodsItem as ApiGoodsItem, FeiyongxiangItem, ListStats } from '@/api/order/types';
import { onLoad } from '@dcloudio/uni-app';
import { computed, ref } from 'vue';
import { delFeiyongxiangData, goodsLists, updatePiciData } from '@/api/order';
import * as S1Header from '@/components/S1Header.vue';

// 定义UI显示的自定义商品类型
interface UIGoodsItem {
  name: string;
  tag: string;
  pieces: string;
  weight: string;
  price: string;
  subtotal: string;
}

// 定义费用项目类型
interface FeeItem {
  id: number;
  name: string;
  amount: string;
  time: string;
  operator: string;
}

// 批次数据
const batchInfo = ref({
  name: '肖士举',
  batchNo: '005',
  time: '2024-12-13 09:39',
  buyer: '张三',
  operator: '肖士举',
  status: 1, // 1: 在售, 2: 售完, 3: 结完
});

// 备注文本
const remarkText = ref('');

// 商品列表 - 使用API返回的完整数据
const goodsList = ref<ApiGoodsItem[]>([]);

// UI展示用的转换后的商品列表
const uiGoodsList = computed<UIGoodsItem[]>(() => {
  return goodsList.value.map(item => ({
    name: item.goods_name,
    tag: item.cat_one?.name || '',
    pieces: item.sell_str || `${item.sell_num}${item.unit}`,
    weight: item.average_weight ? `(${item.mini_type_num}${item.mini_type})` : '',
    price: item.single || '0',
    subtotal: item.all_goods_price || '0',
  }));
});

// 总计信息
const totalInfo = ref<ListStats | null>(null);

// 统计数据，显示在合计行
const statistics = computed(() => {
  if (!totalInfo.value) {
    return {
      sell_total_num: '',
      sell_total_weight: '',
      all_average_weight: '',
      single: '',
      goods_total: '',
    };
  }

  return {
    sell_total_num: totalInfo.value.sell_total_num,
    sell_total_weight: totalInfo.value.sell_total_weight,
    all_average_weight: totalInfo.value.all_average_weight,
    single: totalInfo.value.single,
    goods_total: totalInfo.value.goods_total,
  };
});

// 费用列表
const feesList = ref<FeeItem[]>([]);

// 计算总费用
const totalFees = computed(() => {
  let total = 0;
  feesList.value.forEach((fee) => {
    const amount = Number.parseFloat(fee.amount.replace(/[^0-9.-]/g, ''));
    total += amount;
  });
  return `${total}元`;
});

// 应结金额
const totalToSettle = computed(() => {
  return totalInfo.value?.goods_total || '0';
});

// 导航返回
const onBack = (): void => {
  uni.navigateBack();
};

// 批次售完
const onBatchSold = (): void => {
  uni.showModal({
    title: '确认操作',
    content: '确定标记该批次为售完状态吗？',
    async success(res) {
      if (res.confirm) {
        try {
          const res = await updatePiciData({
            id: Number.parseInt(pageParams.value.id),
            status: 1,
          });
          if (res.code === 200) {
            uni.showToast({
              title: '批次已标记为售完',
              icon: 'success',
            });
            // 重新加载批次详情
            loadBatchDetail(pageParams.value.id);
          }
          else {
            uni.showToast({
              title: res.msg || '操作失败',
              icon: 'none',
            });
          }
        }
        catch (error) {
          console.error('标记批次售完失败', error);
          uni.showToast({
            title: '操作失败',
            icon: 'none',
          });
        }
      }
    },
  });
};

// 去结算
const onSettle = (): void => {
  uni.navigateTo({
    url: `/pages/common/settlement/index?batchId=${batchInfo.value.batchNo}`,
  });
};

// 导航到销售统计页面
const goToSalesStats = (): void => {
  uni.navigateTo({
    url: `/pages/common/salesStats/index?batchId=${batchInfo.value.batchNo}`,
  });
};

// 跳转到添加费用页面
const goToAddFee = (): void => {
  uni.navigateTo({
    url: `/pages/common/addFee/index?batchId=${pageParams.value.id}`,
  });
};

// 显示货品销售详情
const showGoodsDetail = (item: ApiGoodsItem): void => {
  uni.showToast({
    title: `查看${item.goods_name}的销售详情`,
    icon: 'none',
  });
  // TODO: 实现商品销售详情页面跳转
};

// 编辑货品
const editGoods = (item: ApiGoodsItem): void => {
  if (batchInfo.value.status !== 1) return; // 非在售状态不允许编辑

  uni.showToast({
    title: `编辑${item.goods_name}`,
    icon: 'none',
  });
  // TODO: 实现编辑商品功能
};

// 保存页面参数
const pageParams = ref({
  id: '',
});

// 获取页面参数
onLoad((options: any) => {
  if (options.id) {
    pageParams.value.id = options.id;
  }
});
onShow(() => {
  loadBatchDetail(pageParams.value.id);
});

// 加载批次详情
const loadBatchDetail = async (batchId: string) => {
  try {
    // 调用获取批次商品列表API
    const res = await goodsLists({
      goods_name: '',
      index: 2,
      limit: 100,
      page: 1,
      pici_id: Number.parseInt(batchId),
      saleStatus: 1,
    });

    if (res.code === 200 && res.data) {
      // 处理商品数据
      if (res.data.data && res.data.data.data) {
        goodsList.value = res.data.data.data;
      }

      // 设置总计信息
      if (res.data.list) {
        totalInfo.value = res.data.list;
      }

      // 设置批次信息
      if (res.data.data && res.data.data.data && res.data.data.data.length > 0) {
        const piciInfo = res.data.data.data[0].pici_info;
        if (piciInfo) {
          batchInfo.value = {
            name: piciInfo.huozhu_name || '',
            batchNo: piciInfo.pici.toString() || '',
            time: piciInfo.time || '',
            buyer: piciInfo.huozhu?.lxr_name || '',
            operator: '', // 没有相关字段，待确认
            status: piciInfo.status || 1,
          };
        }
      }

      // 设置费用信息
      if (res.data.feiyongxiang && res.data.feiyongxiang.length > 0) {
        feesList.value = res.data.feiyongxiang.map((item: FeiyongxiangItem) => {
          return {
            id: item.id,
            name: item.name,
            amount: `${item.money > 0 ? '+' : ''}${item.money}元`,
            time: item.add_time,
            operator: item.username,
          };
        });
      }
    }
  }
  catch (error) {
    console.error('获取批次详情失败', error);
    uni.showToast({
      title: '获取批次详情失败',
      icon: 'none',
    });
  }
};

// 删除费用项
const deleteFee = async (id: number) => {
  try {
    const res = await delFeiyongxiangData({ id });
    if (res.code === 200) {
      uni.showToast({
        title: '删除成功',
        icon: 'success',
      });
      // 重新加载批次详情
      loadBatchDetail(pageParams.value.id);
    }
    else {
      uni.showToast({
        title: res.msg || '删除失败',
        icon: 'none',
      });
    }
  }
  catch (error) {
    console.error('删除费用项失败', error);
    uni.showToast({
      title: '删除费用项失败',
      icon: 'none',
    });
  }
};
</script>

<style scoped lang="scss">
.page-container {
  width: 100%;
  height: 100vh;
  background-color: #f5f5f5;
  position: relative;
}

.fixed-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 10;
  background-color: #f5f5f5;
}

.batch-header {
  width: 375px;
  height: 96px;
  background: rgba(56, 56, 56, 1);
  box-shadow: 2px 1px 4px rgba(0, 0, 0, 0.25);
  margin: 0 auto;
}

.content-scroll {
  position: absolute;
  top: 160px;
  /* 根据头部高度调整 */
  left: 0;
  right: 0;
  bottom: 80px;
  /* 根据底部高度调整 */
  z-index: 1;
}

.status-tag {
  position: absolute;
  top: 0;
  right: 50rpx;
  width: 43px;
  height: 20px;
  background: rgba(209, 255, 227, 1);
  display: flex;
  justify-content: center;
  align-items: center;
  border-bottom-left-radius: 8px;
  border-bottom-right-radius: 8px;
}

.fixed-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 80px;
  background: white;
  box-shadow: 0 -2px 6px rgba(0, 0, 0, 0.05);
  z-index: 10;
}

.buttons-group {
  display: flex;
  padding: 12px;
  width: 100%;
}

.batch-sold-btn,
.settle-btn {
  flex: 1;
  height: 44px;
  border-radius: 4px;
  font-size: 16px;
  font-weight: 500;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

.batch-sold-btn {
  margin-right: 12px;
  background-color: #ff9800;
  color: white;
}

.settle-btn {
  background-color: #43cf7c;
  color: white;
}

.stats-btn {
  cursor: pointer;
}

.stats-text {
  font-size: 20px;
  font-weight: 400;
  color: rgba(255, 255, 255, 1);
}

/* 订单表格样式 */
.order-table {
  background: white;
  border-collapse: collapse;
  width: 100%;
}

.table-header {
  display: flex;
  background-color: #f9fafb;
  border-bottom: 1px solid #e5e7eb;
  color: #6b7280;
  font-size: 14px;
}

.table-row {
  display: flex;
  border-bottom: 1px solid #e5e7eb;
  min-height: 60px;
}

.total-row {
  background-color: #f9fafb;
  font-weight: bold;
}

.th,
.td {
  padding: 10px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

.goods-info {
  width: 34%;
  text-align: left;
  justify-content: flex-start;
  padding-right: 0;
}

.quantity {
  width: 33%;
}

.price,
.subtotal {
  width: 16%;
}

.subtotal {
  width: 17%;
}

.market-tag {
  display: inline-block;
  padding: 2px 4px;
  border-radius: 2px;
  font-size: 12px;
  margin-top: 4px;
}

.green-market {
  background-color: rgba(52, 211, 153, 0.2);
  color: #0f766e;
}

.yellow-market {
  background-color: rgba(251, 191, 36, 0.2);
  color: #92400e;
}

.weight-text {
  color: #666;
  font-size: 12px;
}

/* 费用部分 */
.fees-section {
  margin-top: 12px;
  background: white;
}

.fee-item {
  padding: 12px 16px;
  border-bottom: 1px solid #e5e7eb;
}

.fee-edit-icon,
.fee-delete-icon {
  width: 20px;
  height: 20px;
  background-size: contain;
  background-repeat: no-repeat;
}

.fee-edit-icon {
  background-image: url("https://ceshiweb.picaime.com/static/images/edit.png");
}

.fee-delete-icon {
  background-image: url("https://ceshiweb.picaime.com/static/images/delete.png");
}

.fee-total {
  padding: 12px 16px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  font-weight: bold;
}

/* 备注区域 */
.remark-area {
  margin-top: 12px;
  background-color: white;
  border-radius: 4px;
  padding: 12px;
}

.remark-textarea {
  width: 100%;
  height: 60px;
  background: transparent;
  border: none;
  font-size: 14px;
  color: #333;
}

/* 添加按钮样式 */
.add-btn {
  background-color: #43cf7c;
  padding: 6px 12px;
  border-radius: 4px;
  color: white;
  font-size: 14px;
}

/* 移除原来的添加按钮样式 */
.add-fee-btn {
  display: none;
}

.guige-tag {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  background-color: #d1ffe3;
  color: #333;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  white-space: nowrap;
  line-height: 20px;
  max-width: 100%;
}
</style>
